package com.woorigil.social.controller.main;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.RedirectView;

import com.woorigil.social.DateUtils;
import com.woorigil.social.controller.BaseController;
import com.woorigil.social.controller.CookieUtils;
import com.woorigil.social.domain.ProviderCode;
import com.woorigil.social.domain.ProviderUtils;
import com.woorigil.social.domain.deal.RecentView;
import com.woorigil.social.domain.deal.RecentViewDao;
import com.woorigil.social.domain.landing.Landing;
import com.woorigil.social.domain.landing.LandingDao;
import com.woorigil.social.domain.point.DealPointDao;

@Controller
public class LandingController extends BaseController {
	@Autowired LandingDao landingDao;
	@Autowired DealPointDao dealPointDao;
	@Autowired RecentViewDao recentViewDao;
	
	@RequestMapping("/landing")
	public RedirectView landing(int dealId, String providerCode, String metaId, HttpServletRequest request, HttpServletResponse response) {
//		Deal socialDeal = DealService.selectDeal(metaId);
//		socialDeal.addClickCount();
		
		Landing landing = new Landing(providerCode, metaId, StringUtils.substring(getUserAgent(), 0, 90), getRemoteAddr());
		landingDao.insert(landing);
		
		String viewDealsCookieValue = CookieUtils.getValue(request, "RECENT_VIEW_DEALS");
		if (StringUtils.isBlank(viewDealsCookieValue)) {
			viewDealsCookieValue = String.valueOf(dealId);
		} else {
			viewDealsCookieValue = String.valueOf(dealId) + "," + viewDealsCookieValue;
		}
		CookieUtils.addCookie(response, "RECENT_VIEW_DEALS", viewDealsCookieValue, DateUtils.ONE_YEAR);
		
		String sid = request.getParameter("sid");
		if (StringUtils.isNotBlank(sid)) {
			RecentView recentView = recentViewDao.selectByDeal(sid, dealId);
			if (recentView == null) {
				recentViewDao.insert(new RecentView(sid, dealId, new Date()));
			} else {
				recentView.setInsertDate(new Date());
				recentViewDao.update(recentView);
			}
		}
		
		dealPointDao.updateClickCount(dealId, 1);
		
		return new RedirectView(ProviderUtils.viewPage(ProviderCode.valueOf(providerCode), metaId));
	}	
}
